package com.liao.badminton.code.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Array;
import java.util.*;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;

/**
 * @description: 处理名字
 * @author: TangMonk
 * @create: 2024-11-04 17:13
 **/
public class NameUtil {
    //正则序号下标
    private static final String REGEX_INDEX = "\\d+[\\.|\\,|\\:|\\;|\\，|\\。|\\：|\\；|\\、]+.*";
    private static final String REGEX_INDEX_REPLACE = "^\\d+[\\.|\\,|\\:|\\;|\\，|\\。|\\：|\\；|\\、]+";
    private static final String sex = ".*\\uD83C\\uDF38|.*\\[玫瑰\\].*|.*\\[凋谢\\]|.*\\uD83C\\uDF37|.*\\uD83C\\uDF39";
    private static final String sex_replace = "\\uD83C\\uDF38|\\[玫瑰\\]|\\[凋谢\\]|\\uD83C\\uDF37|\\uD83C\\uDF39";
    private static final String remark = "\\(.*\\)|\\（.*\\）";
    private static final String textAdd = "＋"; //文本的加号在数据库中需要替换为+
    private static final String dbAdd = "+";

    public static void main(String[] args) {
        List<String> names = CollectionUtil.newArrayList("AnsonAnson1Anson2", "强Ak小红", "A姐红B", "AnsonA谢老师", "LEE软格", "软1格2软3", "对3谢老师");
        names.forEach(name -> {
            if (name.matches("[(A-Za-z)]+")) {
                System.out.println(name);
            }
            System.out.println(findNames(name, 2, null));
        });
        System.out.println(names);
    }


    public static String wipeIndex(String str) {
        if (str.contains(textAdd)) {
            str = str.replaceAll(textAdd, dbAdd);
        }
        return str.replaceAll(" ", "").replaceFirst(REGEX_INDEX_REPLACE, "");
    }

    public static String wipeSex(String str) {
        return str.replaceAll(sex_replace, "");
    }

    public static String wipeRemark(String str) {
        return str.replaceAll(remark, "");
    }

    public static Boolean hasOrderIndex(String str) {
        return str.replaceAll(" ", "").matches(REGEX_INDEX);
    }

    public static Boolean isFemale(String str) {
        return str.matches(sex);
    }

    public static Boolean hasRemark(String str) {
        return str.matches(remark);
    }


    public static List<String> findNames(String text, Integer num, Long groupId) {
        List<String> names = new ArrayList<>();
        String s = text.replaceAll("\\s*", "").replaceAll("[^(\\u4e00-\\u9fa5)]", "");//所有中文
        String s1 = text.replaceAll("\\s*", "").replaceAll("[^(A-Za-z)]", "");//所有英文
        String s2 = text.replaceAll("\\s*", "").replaceAll("[^(0-9)]", "");//所有数字
        String unlessNum = text.replaceAll("\\s*", "").replaceAll("[(0-9)]", "");//所有数字
        if (StrUtil.isNotBlank(s) && StrUtil.isBlank(s1)) {
            if (text.length() == 1 || s.length() == 1) {
                names.add(s);
            } else if (s.length() > 1) { //只有中文名
                //临时处理打水群一个字一个人的情况
                Map<Integer, String> chMap = new HashMap<>();//下标对应中文名
                splitName(text, chMap, 2); //被数字分隔，，
                if (chMap.size() > 1) {
                    if (chMap.size() == num) {
                        names.addAll(chMap.values());
                    } else if (chMap.size() < num) {
                        String LengthName = chMap.values().toArray(new String[0])[0];
                        for (String value : chMap.values()) {
                            if (LengthName.length() < value.length()) {
                                names.add(LengthName);
                                LengthName = value;
                            }
                        }
                        handleChineseName(LengthName, names, groupId, num - names.size());
                    } else {
                        handleChineseName(s, names, groupId, num);
                    }
                } else {
                    handleChineseName(s, names, groupId, num);
                }
            }
        } else if (StrUtil.isNotBlank(s) && StrUtil.isNotBlank(s1)) { //有中文名和英文名
            //ac姐bc哥小红l 怎么处理？
            Map<Integer, String> enMap = new HashMap<>();//下标对应英文名
            splitName(text, enMap, 1);
            Map<Integer, String> chMap = new HashMap<>();//下标对应中文名
            splitName(text, chMap, 2);//a姐B哥，小红l妹，A姐小红，红C蓝B，小红Anson,Anson谢老师，a姐Anson
            if (enMap.size() == 1) { //只有英文名，让这个英文算一个占位符
                Collection<String> values = enMap.values();
                for (String value : values) {
                    if (value.length() > 1 && chMap.size() == 1) {
                        names.add(value);
                        handleChineseName(s, names, groupId, num - names.size());//再处理中文名：缺少人数
                    } else {
                        unlessNum = StrUtil.replace(unlessNum, value, "%"); //将英文换成占位符
                        handleChineseName(unlessNum, names, groupId, num - names.size());//再处理中文名：缺少人数
                        for (String name : names) {
                            if (name.contains("%")) {
                                names.set(names.indexOf(name), name.replaceAll("%", value));
                            }
                        }
                    }
                }
            } else { //有分隔,英文有分隔:Anson软教B姐,a红蓝c,红C蓝B小文
                for (String value : enMap.values()) {
                    if (value.length() > 1) {
                        names.add(value);
                        unlessNum = StrUtil.replace(unlessNum, value, ""); //将英文换成占位符
                    }
                }
                handleChineseName(unlessNum, names, groupId, num - names.size());//再处理中文名：缺少人数
//                }
            }

        } else if (StrUtil.isBlank(s) && StrUtil.isNotBlank(s1)) { //只有英名
            Map<Integer, String> enMap = new HashMap<>();//下标对应中文名
            splitName(text, enMap, 1); //被数字分隔，，
            if (enMap.size() > 1) {
                if (enMap.size() == num) {
                    names.addAll(enMap.values());
                } else if (enMap.size() < num) {
                    String LengthName = enMap.values().toArray(new String[0])[0];
                    for (String value : enMap.values()) {
                        if (LengthName.length() < value.length()) {
                            names.add(LengthName);
                            LengthName = value;
                        }
                    }
                    handleEnglishName(LengthName, names, num - names.size());
                } else {
                    handleEnglishName(s1, names,  num);
                }
            } else {
                handleEnglishName(s1, names,  num);
            }
        }
        if (StrUtil.isNotBlank(s2)) {
            s2.chars().forEach(c -> {
                int indexNum = text.indexOf(c);
                if (indexNum > 0) {
                    Iterator<String> iterator = names.iterator();
                    while (iterator.hasNext()) {
                        String next = iterator.next();
                        String s3 = next + Integer.parseInt(String.valueOf((char) c));
                        if (text.contains(s3)) {
                            names.set(names.indexOf(next), s3);
                            break;
                        }
//                        String name = iterator.next();
//                        if (indexNum - 1 == text.indexOf(name)
//                                ||indexNum - 1 == text.indexOf(name)+name.length()
//                                ||
//                        ) {
//                            names.set(names.indexOf(name), name + Integer.parseInt(String.valueOf((char) c)));
//                            break;
//                        }
                    }
                } else {
                    names.set(0, Integer.parseInt(String.valueOf((char) c)) + names.get(0));
                }

            });
        }

        return names;
    }

    /**
     *
     * @param text
     * @param indexNameMap
     * @param type 1,英文名 2,中文名
     */
    private static void splitName(String text, Map<Integer, String> indexNameMap, int type) {
        String temp = "[A-Za-z]";
        if (type == 2)
            temp = "[(\\u4e00-\\u9fa5)]";
        Integer start = null;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (String.valueOf(c).matches(temp)) {
                if (start == null) {
                    start = i;
                }
                if (i + 1 == text.length()) {
                    indexNameMap.put(start, text.substring(start, i + 1));
                    break;
                } else if (!String.valueOf(text.charAt(i + 1)).matches(temp) || (type == 1 && Character.isUpperCase(text.charAt(i + 1)) && !Character.isUpperCase(text.charAt(i)))) {
                    indexNameMap.put(start, text.substring(start, i + 1));
                    start = null;
                }
            }
        }
    }

    /**
     * @Description: handleChineseName 中文名字处理
     * @Param: text 龙软格  -> 龙,软,格
     * @return: void
     * @Date: 2024/11/4
     */
    private static void handleChineseName(String text, List<String> names, Long groupId, Integer num) {
        if (num == 0) {
            return;
        }
        if (groupId != null && groupId.equals(1L)) {
            text.chars().forEach(c -> names.add(String.valueOf((char) c)));
        } else {
            int sudIndex = text.length() / num;
            for (int i = 0; i < num; i++) {
                if (i == num - 1) {
                    names.add(text.substring(i * sudIndex, text.length()));
                } else {
                    names.add(text.substring(i * sudIndex, (i + 1) * sudIndex));
                }
            }
        }
    }

    /**
     * @Description: handleEnglishName 英文名字处理
     * @Param: text AmyBellaAnson -> Amy,Bella,Anson
     * @return: void
     * @Date: 2024/11/4
     */
    private static void handleEnglishName(String text, List<String> names,Integer num) {
        if (num<1) {
            return;
        }
        List<Integer> lastUpperIndex = new ArrayList<>();
        for (int i = 0; i < text.length(); i++) {
            if (Character.isUpperCase(text.charAt(i))) {
                if (i != 0) {
                    lastUpperIndex.add(i);
                }
            }
        }
        int start = 0;
        if (isNotEmpty(lastUpperIndex)) {
            for (int i = 0; i < lastUpperIndex.size(); i++) {
                names.add(text.substring(start, lastUpperIndex.get(i)));
                start = lastUpperIndex.get(i);
                if (i == lastUpperIndex.size() - 1) {
                    names.add(text.substring(start, text.length()));
                }
            }
        } else {
            names.add(text);
        }
    }

}
